package sketch.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;

public class SketchLog {
	public static FileWriter log = null;

	private static String sep = Globals.fileSep;
	
	public static String default_log_dir = "." + sep + "log";
	public static String default_log_file = "." + sep + "log" + sep + "log.txt";

	public static final String lineSep = System.getProperty("line.separator");

	private SketchLog() {
		throw new IllegalStateException("can not be initialized");
	}

	public static final ByteArrayOutputStream bos;
	public static final PrintStream systemOutErrStream;
	public static final PrintStream err;
	public static final PrintStream out;

	static {
		bos = new ByteArrayOutputStream();
		systemOutErrStream = new PrintStream(bos);
		err = System.err;
		out = System.out;
	}

	public static void configDefaultLog() {
		logConfig(default_log_file);
	}

	public static void logConfig(String logFile) {
		try {
			File f = new File(logFile);
			if(!f.exists()) {
				SketchUtil.createDir(default_log_dir);
				Checker.checkTrue(f.createNewFile(), "Fail to create file: " + logFile);
			}
			SketchLog.log = new FileWriter((logFile));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void log(String s) {
		if (!isLoggingOn())
			return;
		try {
			log.write(s);
			log.flush();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	public static void logln(String s) {
		if (!isLoggingOn())
			return;
		try {
			log.write(s);
			log.write(lineSep);
			log.flush();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	public static boolean isLoggingOn() {
		return log != null;
	}
	
	public static void main(String[] args) {
		configDefaultLog();
	}
}